package com.yunhe.merchants.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.merchants.domain.*;
import com.yunhe.merchants.repository.IDataHistoryProjectStatusRepository;
import com.yunhe.merchants.service.IDataHistoryProjectStatusService;
import com.yunhe.merchants.service.IMyProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: DongWenYu
 * @Date: 2021/5/11 13:44
 */
@Service
public class DataHistoryProjectStatusServiceImpl implements IDataHistoryProjectStatusService {

    private static final Logger logger = LoggerFactory.getLogger(DataHistoryProjectStatusServiceImpl.class);

    @Autowired
    IDataHistoryProjectStatusRepository dataHistoryProjectStatusRepository;

    @Resource(name = "myProjectServiceImpl")
    IMyProjectService myProjectService;


    @Override
    public void insert(ProcessStatus processStatus, MyProject myProject) {
        DataHistoryProjectStatus dataHistoryProjectStatus = covertStatusToHistory(processStatus , myProject);
        dataHistoryProjectStatusRepository.createDataHistoryProjectStatus(dataHistoryProjectStatus);
    }

    @Override
    public PageResult selectByProjectId(Long id, int page, int size) {
        MyProject myProject = myProjectService.selectById(id);
        if (myProject == null){
            logger.info("找不到该项目,id:{}",id);
            return null;
        }else {
            PageHelper.startPage(page,size);
            List<DataHistoryProjectStatus> dataHistoryProjectStatuses = dataHistoryProjectStatusRepository.getHistoryStatusByBusinessId(myProject.getBusinessId());
            PageInfo<DataHistoryProjectStatus> pageInfo = new PageInfo<>(dataHistoryProjectStatuses);
            return new PageResult(page,size, (int) pageInfo.getTotal(),dataHistoryProjectStatuses);
        }
    }

    private DataHistoryProjectStatus covertStatusToHistory(ProcessStatus processStatus , MyProject myProject) {
        DataHistoryProjectStatus dataHistoryProjectStatus = new DataHistoryProjectStatus();
        dataHistoryProjectStatus.setBusinessId(myProject.getBusinessId());
        dataHistoryProjectStatus.setOperator(myProject.getUpdater());
        dataHistoryProjectStatus.setOperatingTime(myProject.getUpdateTime());
        dataHistoryProjectStatus.setStatus(myProject.getCompanyStatus());
        dataHistoryProjectStatus.setDemandArea(processStatus.getAreaRequirement());
        dataHistoryProjectStatus.setRecommendedPlant(String.valueOf(myProject.getRecommendOffice()));
        dataHistoryProjectStatus.setFailureReason(processStatus.getFailReason());
        return dataHistoryProjectStatus;
    }
}
